package com.itlong.cloud.config.filelistener;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class CustomMultipartResolver extends CommonsMultipartResolver {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(FileUploadProgressListener.class);

    @Autowired
    private FileUploadProgressListener listener;

    @Autowired
    RedisService redisService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    private String uploadFilePath = "/faceRecognition/uploadLogFiles";

    @Override
    protected MultipartParsingResult parseRequest(HttpServletRequest request){
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        fileUpload.setProgressListener(listener);
        String sn = "";
        String deviceType = "";
        String deviceUnique = "";
        String fileName = "";
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            log.info("报头数据》》》》》》》》》》》》》" + name + "value>>>>>>>>>>>>>>>>>>>>>>" + request.getHeader(name));
        }

        try {
            if (uploadFilePath.equals(request.getServletPath())){
                deviceUnique = request.getHeader("deviceUnique");
                fileName = request.getHeader("fileName");
                Map<Object, Object> receiveStatus = new HashMap<>();
                receiveStatus.put("phase", 1);
                receiveStatus.put("createTime", new Date());
                receiveStatus.put("fileName", fileName);
                receiveStatus.put("deviceType", 5);
                receiveStatus.put("fileSize", 0);
                receiveStatus.put("uploadStatus", 0);
                redisService.set(deviceUnique, 180L, JSON.toJSONString(receiveStatus));
                listener.setSession(request.getSession(), deviceUnique, deviceType, fileName);
                System.out.println(JSON.toJSONString(receiveStatus));
            }
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return parseFileItems(fileItems, encoding);
        }catch (Exception ex) {
            if (uploadFilePath.equals(request.getServletPath()) && StringUtils.isNotBlank(sn)){
                Map<Object, Object> receiveStatus = new HashMap<>();
                receiveStatus.put("phase", 0);
                receiveStatus.put("createTime", new Date());
                receiveStatus.put("fileName", fileName);
                receiveStatus.put("deviceType", 5);
                receiveStatus.put("deviceUnique", deviceUnique);
                receiveStatus.put("fileSize", 0);
                receiveStatus.put("uploadStatus", -1);
                redisService.set(deviceUnique, 180L, JSON.toJSONString(receiveStatus));
                applicationEventPublisher.publishEvent(new UploadErrorEvent(JSON.toJSONString(receiveStatus)));
            }
            throw new MultipartException("Failed to parse multipart servlet request", ex);

        }
    }
}
